package com.example.RuanJianKeShe.Service.login;

import com.alibaba.fastjson.JSON;
import com.example.RuanJianKeShe.Bean.Teacher;
import com.example.RuanJianKeShe.Dao.impl.TeacherDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;

@WebServlet("/loginTea")
public class loginTea extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        System.out.println(req.getParameter("msg"));
        String tno = req.getParameter("tno");
        HashMap<String,Object> map = new HashMap<>();
        if (tno.equals("")){
            map.put("checkInfo","请输入用户名");
            String jsonString = JSON.toJSONString(map);
            resp.getWriter().write(jsonString);
        }else{
            String teakey = req.getParameter("Teakey");
            String checkCode = req.getParameter("checkCode");
            HttpSession session = req.getSession();
            String checkCode_session = (String) session.getAttribute("checkCode_session");
            session.removeAttribute("checkCode_session");

            if (checkCode_session!=null && checkCode_session.equalsIgnoreCase(checkCode)){
                TeacherDaoImpl teacherDao = new TeacherDaoImpl();
                Teacher login = teacherDao.getTeacherByIdAndKey(Integer.parseInt(tno), teakey);
                if (login==null){
                    map.put("checkInfo","用户名或密码错误");
                    String jsonString = JSON.toJSONString(map);
                    resp.getWriter().write(jsonString);
                }else{
                    session.setAttribute("myTno",login.getTno());
                    session.setAttribute("myTeaKey",login.getTno());
                }
            }else{
                map.put("checkInfo","验证码错误");
                String jsonString = JSON.toJSONString(map);
                resp.getWriter().write(jsonString);
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}
